import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:talk/pojo/User.dart';
import '../api/LoginApi.dart';
import '../api/auth/AuthBase.dart';
import '../api/dio/BaseModel.dart';
import '../api/dio/SPUtils.dart';


class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  // 获取Key用来获取Form表单组件
  GlobalKey<FormState> loginKey = GlobalKey<FormState>();
  late String userName;
  late String password;
  bool isShowPassWord = false;
  bool isLoading = false;
  String? errorMessage;

  // 在Login页面的State类中
  final LoginApi _loginApi = LoginApi();



  void login() async {
    // 读取当前的Form状态
    var loginForm = loginKey.currentState;
    // 验证Form表单
    if (loginForm!.validate()) {
      loginForm.save();

      // 显示加载状态
      setState(() {
        isLoading = true;
        errorMessage = null;
      });

      try {
        // 调用API登录
        // final response = await _loginApi.login(userName, password);
        var numbers = {};
        numbers['username'] = userName;
        numbers['password'] = password;

        final Response response = await LoginApi.getLogin(numbers);

        // 处理登录成功
        if (response.data['code']  == 200) {
          // 解析用户数据
          // User user = User.fromJson(response['token']);
          // await SPUtils.saveToken(response.data['token']);
          await AuthBase().saveToken(response.data['token']);

          Navigator.pushNamed(context, "/");
        } else {
          // 登录失败，显示错误信息
          setState(() {
            errorMessage = response.data['msg'] ?? '登录失败，请重试';
          });
        }


      } catch (e) {
        // 处理异常
        print('登录异常: $e');
        setState(() {
          errorMessage = '网络错误，请检查网络连接';
        });
      } finally {
        // 隐藏加载状态
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  void showPassWord() {
    setState(() {
      isShowPassWord = !isShowPassWord;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form 表单示例'),
        //返回箭头
        automaticallyImplyLeading: false,
      ),
      body: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 100.0, bottom: 10.0),
            child: Text(
              'LOGO',
              style: TextStyle(
                color: Color.fromARGB(255, 53, 53, 53),
                fontSize: 50.0,
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(16.0),
            child: Form(
              key: loginKey,
              child: Column(
                children: <Widget>[
                  Container(
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color.fromARGB(255, 240, 240, 240),
                          width: 1.0,
                        ),
                      ),
                    ),
                    child: TextFormField(
                      decoration: InputDecoration(
                        labelText: '请输入账号',
                        labelStyle: TextStyle(
                          fontSize: 15.0,
                          color: Color.fromARGB(255, 93, 93, 93),
                        ),
                        border: InputBorder.none,
                      ),
                      keyboardType: TextInputType.phone,
                      onSaved: (value) {
                        userName = value!;
                      },
                      validator: (phone) {
                        if (phone == null || phone.isEmpty) {
                          return '请输入账号';
                        }
                        return null;
                      },
                      onFieldSubmitted: (value) {},
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color.fromARGB(255, 240, 240, 240),
                          width: 1.0,
                        ),
                      ),
                    ),
                    child: TextFormField(
                      decoration: InputDecoration(
                        labelText: '请输入密码',
                        labelStyle: TextStyle(
                          fontSize: 15.0,
                          color: Color.fromARGB(255, 93, 93, 93),
                        ),
                        border: InputBorder.none,
                        suffixIcon: IconButton(
                          icon: Icon(
                            isShowPassWord? Icons.visibility : Icons.visibility_off,
                            color: Color.fromARGB(255, 126, 126, 126),
                          ),
                          onPressed: showPassWord,
                        ),
                      ),
                      obscureText:!isShowPassWord,
                      onSaved: (value) {
                        password = value!;
                      },
                      validator: (pass) {
                        if (pass == null || pass.isEmpty) {
                          return '请输入密码';
                        }
                        return null;
                      },
                    ),
                  ),
                  // 显示错误信息
                  if (errorMessage != null)
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      padding: EdgeInsets.all(8.0),
                      decoration: BoxDecoration(
                        color: Colors.red.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(4.0),
                      ),
                      child: Text(
                        errorMessage!,
                        style: TextStyle(color: Colors.red),
                      ),
                    ),
                  Container(
                    height: 45.0,
                    margin: EdgeInsets.only(top: 20.0),
                    child: SizedBox.expand(
                      child: ElevatedButton(
                        onPressed: isLoading ? null : login,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Color.fromARGB(255, 61, 203, 128),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(45.0),
                          ),
                        ),
                        child: isLoading
                            ? CircularProgressIndicator(color: Colors.white)
                            : Text(
                          '登录',
                          style: TextStyle(
                            fontSize: 14.0,
                            color: Color.fromARGB(255, 255, 255, 255),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30.0),
                    padding: EdgeInsets.only(left: 8.0, right: 8.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Container(
                          child: Text(
                            '注册账号',
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Color.fromARGB(255, 53, 53, 53),
                            ),
                          ),
                        ),
                        Text(
                          '忘记密码？',
                          style: TextStyle(
                            fontSize: 13.0,
                            color: Color.fromARGB(255, 53, 53, 53),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

